package com.dcjt.firehotcarpad.fragment

import NewMessagePool
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aries.library.fast.basis.BasisFragment
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.util.SizeUtil
import com.aries.library.fast.util.ToastUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firecommand.entity.RecordData
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.entity.BaseEntity
import com.dcjt.firehotcarpad.entity.SxhNr
import com.dcjt.firehotcarpad.entity.Sxxx
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.model.FreeDocumentViewModel
import com.dcjt.firehotcarpad.model.HandleDisasterViewModel
import com.dcjt.firehotcarpad.utils.MediaUtils
import com.dcjt.firehotcarpad.widget.MultipleFilePopupView
import com.dcjt.firehotcarpad.widget.RecordPopupWindow
import com.dcjt.firehotcarpad.widget.TimelineDecoration
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.marno.easystatelibrary.EasyStatusView
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
import okhttp3.internal.notifyAll
import java.io.File

/**
 * 灾情动态
 */
class FreeDocumentFragment : BasisFragment(), NewMessagePool.NewMessageObserverObserver {

    private lateinit var viewModel: FreeDocumentViewModel
    private lateinit var easyStatusView: EasyStatusView


    override fun getContentLayout() = R.layout.fragment_free_document

    private var zqId: String? = null

    override fun initView(savedInstanceState: Bundle?) {
        findViewById<RecyclerView>(R.id.rvList).run {
            this?.layoutManager = LinearLayoutManager(context)
            this?.addItemDecoration(
                TimelineDecoration(
                    SizeUtil.dp2px(40f),
                    SizeUtil.dp2px(12f),
                    ContextCompat.getDrawable(requireContext(), R.drawable.ic_item_selected)!!,
                    SizeUtil.dp2px(24f),
                    1
                )
            )
            this?.adapter = mAdapter
        }

        easyStatusView = findViewById(R.id.easyStatus)!!

        NewMessagePool.get().registerNewMessageObserver(this)

        viewModel = ViewModelProvider(this).get(FreeDocumentViewModel::class.java)
        easyStatusView.loading()

        viewModel.requestStatusLiveData.observeForever {
            easyStatusView.content()
            if (it.code == BaseEntity.err) {
                ToastUtil.show("时序化数据请求失败")
                easyStatusView.error()
            } else {
                if (it.data.isNullOrEmpty()) {
                    // 设置空布局
//                    mAdapter.setEmptyView(R.layout.empty.layout)
                    easyStatusView.empty()
                } else {
                    mAdapter.setNewData(it.data)
                    mAdapter.notifyDataSetChanged()
                }
            }
        }

        val handleViewModel =
            ViewModelProviders.of(requireActivity()).get(HandleDisasterViewModel::class.java)
        handleViewModel.getDisasterInfo().observe(this, androidx.lifecycle.Observer { entity ->
            entity.clxx?.cfCjxxId?.let {
                zqId = it
                viewModel.getSxhList(it)
            }
        })
    }


    override fun onReceiveFireDocument() {
        zqId?.let {
            viewModel.getSxhList(it)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        NewMessagePool.get().unRegisterNewMessageObserver(this)
    }

    private val mAdapter =
        object : BaseQuickAdapter<Sxxx, BaseViewHolder>(R.layout.item_timeline_layout) {

            override fun convert(helper: BaseViewHolder, item: Sxxx) {
                val sxhNr = Gson().fromJson<SxhNr>(item.content, SxhNr::class.java)
                if (item.czlx == "12" || item.czlx == "35") {
                    sxhNr.text = sxhNr.text.replace("|\$|", "")
                }
                helper.setText(R.id.tv_date, item.time)
                    .setText(R.id.tv_title, sxhNr.lx)
                    .setText(R.id.tv_info, sxhNr.text)
                    .setTextColor(R.id.tv_info, Color.parseColor("#4B4B4B"))
                    .setVisible(R.id.tv_info, true)
                helper.setGone(R.id.tv_info, !TextUtils.isEmpty(sxhNr.text))
                val mp3List = mutableListOf<String>()
                val imgList = mutableListOf<String>()
                val videoList = mutableListOf<String>()
                val ctiList = mutableListOf<String>()
                for (lx in sxhNr.links) {
                    // 防止后台数据导致App崩溃
                    try {
                        when (lx.key) {
                            "audio" -> mp3List.add(lx.value)
                            "ctivoice" -> ctiList.add(lx.value)
                            "image" -> imgList.add(lx.value)
                            "video" -> videoList.add(lx.value)
                            "id" -> helper.setText(R.id.tv_info, "点击查看${sxhNr.lx}")
                                .setTextColor(
                                    R.id.tv_info,
                                    ContextCompat.getColor(mContext, R.color.mainColor)
                                )
                                .getView<View>(R.id.tv_info).setOnClickListener {
                                    when (item.czlx) {
                                        "20" -> {
                                            /** 现场信息
                                            mLoading.show()
                                            viewModel.getXcXxById(lx.value) */
                                        }
                                        "23" -> {
                                            /** 灾情动态
                                            mLoading.show()
                                            viewModel.getFreeDocument(lx.value) */
                                        }
                                        "22" -> {
                                            /** 文电文书
                                            mLoading.show()
                                            viewModel.getDocumentInfo(lx.value) */
                                        }
                                    }
                                }
                        }
                    } catch (e: Exception) {
                        LoggerManager.e("时序化数据加载失败 ${e.message}")
                    }
                }
                if (mp3List.isEmpty() && imgList.isEmpty() && videoList.isEmpty() && ctiList.isEmpty()) {
                    helper.setGone(R.id.layout_file, false)
                } else {
                    helper.setVisible(R.id.layout_file, true)
                    // 多媒体信息 音视频 图片展示
                    showFile(imgList, mp3List, videoList, ctiList, helper)
                }

            }

        }

    private fun showFile(
        imgList: List<String>,
        mp3List: List<String>,
        mp4List: List<String>,
        ctiList: List<String>,
        helper: BaseViewHolder
    ) {
        if (imgList.isEmpty()) {
            helper.getView<RelativeLayout>(R.id.layout_image).visibility = View.GONE
        } else {
            loadImage(imgList, helper)
        }
        if (mp4List.isEmpty()) {
            helper.getView<RelativeLayout>(R.id.layout_video).visibility = View.GONE

        } else {
            loadVideo(helper, mp4List)
        }
        if (mp3List.isEmpty() && ctiList.isEmpty()) {
            helper.getView<RelativeLayout>(R.id.layout_audio).visibility = View.GONE

        } else if (ctiList.isNotEmpty()) {
            helper.setVisible(R.id.layout_audio, true)
            helper.setText(R.id.tv_audio, "录音 ${ctiList.size}段")
            helper.getView<RelativeLayout>(R.id.layout_audio).setOnClickListener {
                val baseUrl = DataManager.getInstance().appConfigEntity.appServerUrl.logUrl + "/"
                if (ctiList.size > 1) {
                    XPopup.Builder(context).asCustom(
                        MultipleFilePopupView(
                            ctiList,
                            true,
                            mContext,
                            true
                        )
                    ).show()
                } else {
                    XPopup.Builder(context)
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .asCustom(RecordPopupWindow(mContext, true).apply {
                            this.initData(
                                mutableListOf(
                                    RecordData(
                                        File(ctiList.first()).name ?: "未命名文件",
                                        "",
                                        "",
                                        baseUrl + ctiList.first()
//                                        "http://182.150.35.222:8813/new_bigdisaster.wav"
                                    )
                                ), 0
                            )
                        })
                        .show()
//                    if (MediaManager.isPlaying()) {
//                        MediaManager.release()
//                        return@setOnClickListener
//                    }
//                    MediaManager.playSound(
////                        baseUrl + ctiList.first()
//                        "http://182.150.35.222:8813/new_bigdisaster.wav"
//                    ) { mediaPlayer: MediaPlayer? ->
//                    }
                }
            }
        } else {
            helper.setVisible(R.id.layout_audio, true)
            helper.setText(R.id.tv_audio, "音频 ${mp3List.size}段")
            helper.getView<RelativeLayout>(R.id.layout_audio).setOnClickListener {
                val baseUrl = DataManager.getInstance().appConfigEntity.appServerUrl.logUrl + "/"
                if (mp3List.size > 1) {
                    XPopup.Builder(context).asCustom(
                        MultipleFilePopupView(
                            mp3List,
                            true,
                            mContext,
                            false
                        )
                    ).show()
                } else {
                    XPopup.Builder(context)
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .asCustom(RecordPopupWindow(mContext, true).apply {
                            this.initData(
                                mutableListOf(
                                    RecordData(
                                        File(mp3List.first()).name ?: "未命名文件",
                                        "",
                                        "",
                                        baseUrl + mp3List.first()
                                    )
                                ), 0
                            )
                        })
                        .show()
//                    if (MediaManager.isPlaying()) {
//                        MediaManager.release()
//                        return@setOnClickListener
//                    }
//                    MediaManager.playSound(
//                        baseUrl + mp3List.first()
////                        "http://182.150.35.222:8813/new_bigdisaster.wav"
//                    ) { mediaPlayer: MediaPlayer? ->
//                    }
                }
            }
        }
    }

    /**
     * 图片预览
     */
    private fun loadImage(
        imgList: List<String>,
        helper: BaseViewHolder
    ) {
        helper.setVisible(R.id.layout_image, true)
        val baseUrl = DataManager.getInstance().appConfigEntity.appServerUrl.logUrl + "/"
        Glide.with(mContext).load(baseUrl + imgList.first())
            .into(helper.getView(R.id.iv_img))
        helper.setText(R.id.tv_img, "图片 ${imgList.size}张")
        helper.getView<View>(R.id.layout_image).setOnClickListener {
            MediaUtils.showMultiImage(
                mContext,
                imgList,
                helper.getView(R.id.iv_img),
                { _, _ -> })
        }
    }

    private fun loadVideo(helper: BaseViewHolder, mp4List: List<String>) {
        helper.setVisible(R.id.layout_video, true)
        val baseUrl = DataManager.getInstance().appConfigEntity.appServerUrl.logUrl + "/"
        Glide.with(mContext).setDefaultRequestOptions(RequestOptions().frame(1000000).centerCrop())
            .load(baseUrl + mp4List.first()).into(helper.getView(R.id.iv_video))
        helper.setText(R.id.tv_video, "视频 ${mp4List.size}段")
        helper.getView<View>(R.id.layout_video).setOnClickListener {
            if (mp4List.size > 1) {
                XPopup.Builder(context)
                    .asCustom(MultipleFilePopupView(mp4List, false, mContext, false)).show()
            } else {
                // 视频预览
//                FilePreViewActivity.startActivity(FilePreViewActivity.VideoDetailInfo(File(mp4List.first()).name ?: "未命名文件",
//                    baseUrl + mp4List.first()), context)
                JCVideoPlayerStandard.startFullscreen(
                    context,
                    JCVideoPlayerStandard::class.java,
                    baseUrl + mp4List.first(),
                    File(mp4List.first()).name ?: "未命名文件"
                )
            }
        }
    }
}